package com.hlw.springboot.controller;

import com.hlw.springboot.constants.UserConstants;
import com.hlw.springboot.entity.SysPermission;
import com.hlw.springboot.entity.SysRole;
import com.hlw.springboot.entity.SysUser;
import com.hlw.springboot.mapper.SysRoleMapper;
import com.hlw.springboot.util.DataResult;
import com.hlw.springboot.util.IpConfig;
import com.hlw.springboot.util.R;
import com.hlw.springboot.util.ToLayuiTableUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sysRole")
public class SysRoleController {
    @Resource
    private SysRoleMapper sysRoleMapper;


    /**
     *
     * 角色列表
     */
    @PostMapping("/layui")
    @ApiOperation(value = "layui列表")
    public R layuiList(@RequestBody Map<String, Object> map) {
        ToLayuiTableUtil.toMysqlPage(map);
        ToLayuiTableUtil toLayuiTable = ToLayuiTableUtil.setMap(map);
        Map<String, Object> data = toLayuiTable.getData();
        List<SysRole> list = sysRoleMapper.list(data, toLayuiTable.getPage(), toLayuiTable.getLimit());
        int count = sysRoleMapper.count(data);
        return R.ok().put("code", 0).put("data", list).put("count", count);
    }

    /**
     * 编辑角色
     */
    @PostMapping(value = "/saveRole")
    public DataResult innserUser(@ModelAttribute("sysRole") SysRole sysRole) {
        if(sysRole.getId()==null){
           int count = sysRoleMapper.checktByName(sysRole.getName());
           if(count>0){
               return new DataResult(404,"该标识已存在！");
           }else{
                sysRoleMapper.insert(sysRole);
                return new DataResult(1, "保存成功");
           }
        }else{

        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
            return new DataResult(1,"修改成功");
        }
    }


    /**
     * 根据Id获取角色
     */
    @RequestMapping("/findById")
    public DataResult checkUsername(int roleId){
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(roleId);
        return new DataResult(1,sysRole);
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/delRole")
    public DataResult delUser(int roleId){
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(roleId);
        if(sysRole.getName().equals("admin")){
            return new DataResult(401,"该角色不准删除");
        }else{
            sysRoleMapper.deleteByPrimaryKey(roleId);
            return new DataResult(1,"删除成功");
        }
    }

    /**
     * 获取全部角色
     */
    @RequestMapping("/findAll")
    public DataResult findAll(){
        List<SysRole> sysRoleList = sysRoleMapper.findAll();
        return new DataResult(1,sysRoleList);
    }

}
